import { PlusOutlined } from "@ant-design/icons";
import { BetaSchemaForm } from "@ant-design/pro-components";
import ProTable, { ActionType } from "@ant-design/pro-table";
import type { CrudFilters } from "@refinedev/core";
import { SysAttachment, SysAttachmentCategory } from "@sker/model";
import { Button, Card, Image, Modal, Popconfirm } from "antd";
import { useEffect, useRef, useState } from "react";
import { useModel } from "../factory";
import { useModal } from "../useModal";
import { toWebUrl } from "../axios";
import { useForm } from "../useForm";
import { SkerUploadOne } from "./upload-one";
import { AttachmentCategorySelector } from "./attachment-category-selector";
import { useModalForm } from "../useModalForm";
export const AttachmentPrview: React.FC<{ hash: any[] }> = ({ hash }) => {
    const model = useModel(SysAttachment)
    const [list, setList] = useState<any[]>([])
    useEffect(() => {
        if(!hash) return;
        model.findAll([
            'id',
            'from',
            'type',
            'hash',
            'url',
            'hash_url',
            'from'
        ], [{
            field: 'hash',
            operator: 'in',
            value: hash
        }]).then(res => {
            setList(res.data)
        })
    }, [])
    const getSrc = (item: any)=>{
        if(item.from === 's3'){
            return item.hash_url
        }else{
            return item.url;
        }
    }
    return <>
        {list.map(item=>{
            if((item.type as string).startsWith('image')){
                return <img key={item.id} src={getSrc(item)}/>
            }
        })}
    </>
}
export const AttachmentSelectModal: React.FC<{ multi?: boolean, value: any[], onSelect: (val: any[]) => void }> = ({ multi, value, onSelect }) => {
    const { props: modalProps, setOpen } = useModal('选择图片')
    return <div className="flex">
        <Modal {...modalProps} width={'1050px'}>
            <AttachmentSelector multi={!!multi} value={value} onSelect={e => {
                if (multi) {
                    onSelect(e)
                } else {
                    if (e.length > 0) {
                        onSelect(e[0])
                    }
                }
                setOpen(false)
            }} />
        </Modal>
        <AttachmentPrview hash={value} />
        <Button type={'dashed'} onClick={e => setOpen(true)}>+</Button>
    </div>
}
export const AttachmentSelector: React.FC<{ multi?: boolean, value: any[], onSelect: (keys: any[]) => void }> = ({ multi, value, onSelect }) => {
    const model = useModel(SysAttachment)
    const uploadUrl = toWebUrl('imeepos/core/attachment')
    const category = useModel(SysAttachmentCategory)
    const [pres, setPres] = useState<string[]>()
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>(value ? value : [])
    const actionRef = useRef<ActionType>()
    const { formProps, form, setOpen, setTitle, modalProps, record } = useModalForm({
        title: '添加附件',
        columns: async () => {
            const categoryEnum = await category.findAll(['id', 'title']).then(res => {
                const data = {}
                res.data.map(it => {
                    Reflect.set(data, it.id, it.title)
                })
                return data;
            })
            return [
                { dataIndex: 'category_id', title: '文件分类', valueType: 'select', valueEnum: categoryEnum },
                { dataIndex: 'name', title: '文件名' },
                { dataIndex: 'url', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'id', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'bucket', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'from', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'hash', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'type', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                { dataIndex: 'tags', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                {
                    title: '附件',
                    renderFormItem(schema, config, form, action) {
                        const id = form.getFieldValue('id')
                        const name = form.getFieldValue('name')
                        const url = form.getFieldValue('url')
                        const fileList: any[] = [];
                        if (id) {
                            fileList.push({
                                uid: id,
                                url: url,
                                name: name,
                            })
                        }
                        return <SkerUploadOne value={fileList} action={uploadUrl} onUpload={(values) => {
                            form.setFieldsValue({ ...values })
                        }} />
                    },
                },
            ]
        },
        onFinish: async (values) => {
            if (record) {
                values.id = record.id;
            }
            if (pres && pres.length > 0) {
                values.category_id = pres[0]
            }
            values.tags = (values.tags||[]).join(',')
            await model.save(values, ['id'])
            setOpen(false)
            actionRef.current?.reload();
        }
    })
    useEffect(() => {
        if (!record) {
            form.resetFields()
        }
        form.setFieldsValue(record)
    }, [record])
    return <div className="flex">
        <div className="w-300px">
            <AttachmentCategorySelector onSelect={(keys: string[]) => {
                if (keys.length > 0) {
                    form.setFieldValue('type', keys[0])
                }
                setPres(keys)
            }} />
        </div>
        <div className="flex-1 ml-24px">
            <Modal {...modalProps}>
                <BetaSchemaForm {...formProps} />
            </Modal>
            <Card title={'附件列表'} extra={
                <>
                    <Button icon={<PlusOutlined />} type={'primary'} size="small" onClick={() => {
                        setOpen(true)
                    }}></Button>
                </>
            }>
                <ProTable
                    search={false}
                    toolBarRender={false}
                    actionRef={actionRef}
                    rowKey={record => record.hash}
                    rowSelection={{
                        type: multi ? 'checkbox' : 'radio',
                        selectedRowKeys: selectedRowKeys,
                        onChange(selectedRowKeys, selectedRows, info) {
                            setSelectedRowKeys(selectedRowKeys)
                        },
                    }}
                    tableAlertRender={(props) => {
                        return <div className="flex">
                            <div className="flex-1"></div>
                            <Button type={'primary'} onClick={e => {
                                onSelect(props.selectedRowKeys)
                            }}>确认选择</Button>
                        </div>
                    }}
                    columns={[
                        { title: '名称', dataIndex: 'name' },
                        {
                            title: '资源', dataIndex: 'url', render(dom, entity, index, action, schema) {
                                return <Image width={'32px'} src={entity.url} />
                            },
                        },
                        {
                            title: '操作',
                            align: 'right',
                            render(dom, entity, index, action, schema) {
                                return <>
                                    <Button size={'small'} type={'link'} onClick={e => {
                                        setTitle('编辑附件')
                                        setOpen(true, entity)
                                    }}>编辑</Button>
                                    <Popconfirm onConfirm={async e => {
                                        await model.delete(entity.id)
                                        await actionRef.current?.reload();
                                    }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                        <Button size={'small'} type={'link'} danger >删除</Button>
                                    </Popconfirm>
                                </>
                            },
                        }
                    ]}
                    params={{
                        pres
                    }}
                    request={async (params) => {
                        const filters: CrudFilters = [];
                        if (params.pres && params.pres.length > 0) {
                            filters.push({ field: 'category_id', operator: 'in', value: params.pres })
                        }
                        return model.find(['id', 'url', 'name', 'type', 'hash', 'hash_url', 'from', 'bucket'], [
                            ...filters
                        ], [{ field: 'create_date', order: 'desc' }], {
                            current: params.current,
                            pageSize: params.pageSize
                        })
                    }}
                />
            </Card>
        </div>
    </div>
}
